import os
import shutil
import pymysql

# 数据库配置（与main.py一致）
MYSQL_HOST = "115.190.105.70"
MYSQL_PORT = 3307
MYSQL_USER = "root"
MYSQL_PASSWORD = "123456"
MYSQL_DB = "mind_elevation_assistant"

# 固定目标路径
MAIN_DST = r"C:\A\graduation_project\experiment\MindElevationAssistant\ema-admin\src\main"
VUE_DST = r"C:\A\graduation_project\experiment\frontend\src"

def execute_sql_file(cursor, file_path):
    with open(file_path, 'r', encoding='utf-8') as f:
        sql_content = f.read()
    for statement in sql_content.split(';'):
        stmt = statement.strip()
        if stmt:
            cursor.execute(stmt)

def run_sql():
    current_dir = os.path.abspath(os.path.dirname(__file__))
    sql_files = [f for f in os.listdir(current_dir) if f.endswith('.sql')]
    if len(sql_files) == 0:
        print(f"❌ 当前目录没有找到SQL文件: {current_dir}")
        return
    if len(sql_files) > 1:
        print(f"❌ 当前目录存在多个SQL文件，请确保只有一个: {sql_files}")
        return
    sql_file = sql_files[0]
    file_path = os.path.join(current_dir, sql_file)
    try:
        conn = pymysql.connect(
            host=MYSQL_HOST,
            port=MYSQL_PORT,
            user=MYSQL_USER,
            password=MYSQL_PASSWORD,
            database=MYSQL_DB,
            autocommit=True,
            charset='utf8mb4'
        )
        cursor = conn.cursor()
        print(f"执行SQL文件: {file_path}")
        execute_sql_file(cursor, file_path)
        cursor.close()
        conn.close()
        print("✅ SQL文件执行完成")
    except Exception as e:
        print(f"❌ 执行SQL出错: {e}")

def copy_folder(src_folder, dst_folder):
    if not os.path.exists(src_folder):
        print(f"❌ 源文件夹不存在: {src_folder}")
        return
    if not os.path.exists(dst_folder):
        os.makedirs(dst_folder)
        print(f"已创建目标文件夹: {dst_folder}")
    for root, dirs, files in os.walk(src_folder):
        rel_path = os.path.relpath(root, src_folder)
        target_root = os.path.join(dst_folder, rel_path) if rel_path != '.' else dst_folder
        if not os.path.exists(target_root):
            os.makedirs(target_root)
        for file in files:
            src_file = os.path.join(root, file)
            dst_file = os.path.join(target_root, file)
            shutil.copy2(src_file, dst_file)
            print(f"已拷贝: {src_file} -> {dst_file}")

def main():
    print("1. 正在执行SQL文件...")
    run_sql()
    print(f"\n2. 正在拷贝 main 文件夹到: {MAIN_DST}")
    copy_folder('main', MAIN_DST)
    print(f"正在拷贝 vue 文件夹到: {VUE_DST}")
    copy_folder('vue', VUE_DST)
    print("\n✅ 所有操作已完成！")  

if __name__ == "__main__":
    main() 